package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.dto.InspectFinishedProductDto;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.InspectFinishedProductService;
import com.foreverwin.mes.lims.model.InspectFinishedProduct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 *
 * @author Levy
 * @since 2020-03-06
 */
@Controller
@RequestMapping("/inspectFinishedProducts")
public class InspectFinishedProductController {
    private final Logger logger = LoggerFactory.getLogger(InspectFinishedProductController.class);

    @Autowired
    public InspectFinishedProductService inspectFinishedProductService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getInspectFinishedProductById(@PathVariable String id) {
        InspectFinishedProduct result;
        try {
            result = inspectFinishedProductService.selectById(id);
        } catch (Exception e) {
            logger.error("getInspectFinishedProductById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getInspectFinishedProductList(InspectFinishedProduct inspectFinishedProduct){
        List<InspectFinishedProduct> result;
        try {
            EntityWrapper<InspectFinishedProduct> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectFinishedProduct);
            result = inspectFinishedProductService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectFinishedProductList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getInspectFinishedProductPageList")
    public AjaxResult getInspectFinishedProductPageList(FrontPage<InspectFinishedProduct> frontPage, InspectFinishedProduct inspectFinishedProduct){
        Page result;
        try {
            String site = CommonMethods.getSite();
            inspectFinishedProduct.setSite(site);
            EntityWrapper<InspectFinishedProduct> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectFinishedProduct);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("taskId", frontPage.getGlobalQuery())
                    .or().like("inspectionBatch", frontPage.getGlobalQuery())
                    .or().like("product", frontPage.getGlobalQuery())
                    .or().like("projectDesc", frontPage.getGlobalQuery())
                    .or().like("inventory", frontPage.getGlobalQuery())
                    .or().like("checkResult", frontPage.getGlobalQuery())
                    .or().like("ncCode", frontPage.getGlobalQuery())
                    .or().like("inspector", frontPage.getGlobalQuery())
                    .or().like("operation", frontPage.getGlobalQuery())
                    .or().like("createdUser", frontPage.getGlobalQuery())
                    .or().like("updatedUser", frontPage.getGlobalQuery())
        ;
            }
            result = inspectFinishedProductService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectFinishedProductPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param inspectFinishedProduct  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult inspectFinishedProductSave(@RequestBody InspectFinishedProduct inspectFinishedProduct) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        int count;
        try {
            String bo = StringUtils.genHandle(HandleBOConstants.INSPECT_FINISHED_PRODUCT_BO,site,inspectFinishedProduct.getTaskId());
            InspectFinishedProduct oldModel = inspectFinishedProductService.selectById( bo );
            if ( oldModel != null ){
                throw BusinessException.build("成品任务【"+ inspectFinishedProduct.getTaskId() + "】不可重复操作!");
            }
            inspectFinishedProduct.setHandle( bo );
            inspectFinishedProduct.setSite( site );
            inspectFinishedProduct.setCreatedDateTime( new Date() );
            inspectFinishedProduct.setCreatedUser( user );
            count = inspectFinishedProductService.insertOrUpdate(inspectFinishedProduct) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectFinishedProductSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : inspectFinishedProduct);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult inspectFinishedProductDelete(@PathVariable("id") String id){
        int count;
        try {
            count = inspectFinishedProductService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectFinishedProductDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = inspectFinishedProductService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectFinishedProductBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    @ResponseBody
    @GetMapping("/getInspectFinishedProduct")
    public AjaxResult getInspectFinishedProduct(InspectFinishedProductDto inspectFinishedProductDto){
         List<InspectFinishedProduct>   inspectFinishedProducts;
        try {
            inspectFinishedProducts = inspectFinishedProductService.getInspectFinishedProduct( inspectFinishedProductDto );
        } catch (Exception e) {
            logger.error("getInspectFinishedProduct -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success( inspectFinishedProducts );
    }
}